package com.cj.designpattern.observer.Observerable;

import com.cj.designpattern.observer.Observer.Observer;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: WechatServer <br/>
 * Function: 被观察者，实现了Observerable接口 <br/>
 * date: 2018/04/27 14:24 <br/>
 *
 * @author chenj
 * @version 1.0.0
 * @since JDK 1.8
 */
public class WechatServer implements Observerable {

    /**
     * 注意到这个List集合的泛型参数为Observer接口，设计原则：面向接口编程而不是面向实现编程
     */
    private List<Observer> list;
    private String message;

    public WechatServer() {
        list = new ArrayList<>();
    }

    @Override
    public void registerObserver(Observer o) {
        list.add(o);
    }

    @Override
    public void removeObserver(Observer o) {
        if (list.isEmpty()) {
            return;
        }
        list.remove(o);
    }

    @Override
    public void notifyObserver() {
        if (list.isEmpty()) {
            return;
        }
        list.forEach(observer -> observer.update(message));
    }

    public void sendMessage(String message) {
        this.message = message;
        System.out.println("微信服务更新消息：" + message);
        notifyObserver();
    }
}
